using System;
using System.IO;
using System.Reflection;

namespace SevenZSharp
{
   public class RegressionTests
   {
      public void TestAll()
      {
         MethodInfo[] methods = GetType().GetMethods();
         foreach (MethodInfo method in methods)
         {
            if (method.IsPublic && !method.IsStatic && method.Name.StartsWith("Test") && method.Name != "TestAll")
            {
               method.Invoke(this, null);
            }
         }
      }

      public void Test()
      {
         foreach (CompressionFormat format in new CompressionFormat[]
            {
               CompressionFormat.SevenZ, CompressionFormat.Zip, CompressionFormat.Tar
            })
         {
            string ext = CompressionEngine.GetCompressionExtension(format);
            CompressionEngine.Current.Encoder.EncodeFromDirectory(@"..\..\..\7zSharp\SevenZip", "lzma." + ext);
            CompressionEngine.Current.Decoder.DecodeIntoDirectory("lzma." + ext, "lzmaout");

            CompressionEngine.Current.Encoder.EncodeSingleFile(@"..\..\..\7zSharp\LGPL.txt", "LGPL-enc." + ext);
            CompressionEngine.Current.Decoder.DecodeSingleFile(@"LGPL-enc." + ext, "LGPL.txt");
            if (!CompareFiles(@"..\..\..\7zSharp\LGPL.txt", "LGPL.txt"))
            {
               throw new Exception("Files are not equal");
            }
         }
      }

      public bool CompareFiles(string file1, string file2)
      {
         using (FileStream fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read))
         {
            using (FileStream fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read))
            {
               int b1;
               while ((b1 = fs1.ReadByte()) != -1)
               {
                  int b2 = fs2.ReadByte();

                  if (b2 == -1)
                  {
                     return false;
                  }

                  if (b1 != b2)
                  {
                     return false;
                  }
               }

               if (fs2.ReadByte() != -1)
               {
                  return false;
               }

               return true;
            }
         }
      }
   }
}